//树所需数据
var treedata = [
	{
		id:'01',
		name:'funtree 01',
		pid:''
	},
	{
		id:'0101',
		name:'funtree 0101',
		pid:'01'
	},
	{
		id:'010101',
		name:'funtree 010101',
		pid:'0101'
	},
	{
		id:'010102',
		name:'funtree 010102',
		pid:'0101'
	},
	{
		id:'0102',
		name:'funtree 0102',
		pid:'01'
	},
	{
		id:'010201',
		name:'funtree 010201',
		pid:'0102'
	},
	{
		id:'02',
		name:'funtree 02',
		pid:''
	},
	{
		id:'0201',
		name:'funtree 0201',
		pid:'02'
	},
	{
		id:'020101',
		name:'funtree 020101',
		pid:'0201'
	},
	{
		id:'0202',
		name:'funtree 0202',
		pid:'02'
	},
	{
		id:'020201',
		name:'funtree 020201',
		pid:'0202'
	},
	{
		id:'020202',
		name:'funtree 020202',
		pid:'0202'
	},
	{
		id:'0203',
		name:'funtree 0203',
		pid:'02'
	},
	{
		id:'020301',
		name:'funtree 020301',
		pid:'0203'
	},
	{
		id:'020302',
		name:'funtree 020302',
		pid:'0203'
	},
	{
		id:'020303',
		name:'funtree 020303',
		pid:'0203'
	},
	{
		id:'03',
		name:'funtree 03',
		pid:''
	},
	{
		id:'0301',
		name:'funtree 0301',
		pid:'03'
	},
	{
		id:'04',
		name:'funtree 04',
		pid:''
	}
]

/* 参数是不是空或没定义 */
function isFtUndef (v) {
    return v === undefined || v === null || v === ''
  }
/* 参数非空 */
function isFtDef (v) {
    return v !== undefined && v !== null && v !== ''
  }

function isTrue (v) {
    return v === true
  }

function isFalse (v) {
    return v === false
  }

  /**
   * 检查参数是不是原始的数据类型.
   */
function isPrimitive (value) {
    return (
      typeof value === 'string' ||
      typeof value === 'number' ||
      // $flow-disable-line
      typeof value === 'symbol' ||
      typeof value === 'boolean'
    )
  }

  /**
   * 检查参数是不是一个object
   */
function isObject (obj) {
    return obj !== null && typeof obj === 'object'
  }

/* 返回一个完整的树对象 */
function complete(obj){
	//返回一个树形嵌套对象
	let completeTreeObj = {
		id:'',
		name:'funtreeRoot',
		pid:'',
		sonList:[]
	}
	
	
	//将obj转为map，并为其绑上子节点
	const arrChangeMap = (arr) => new Map(arr.map( (value) => [value.id,value]))
	let treeMap = arrChangeMap(obj)
	obj.forEach((val,index) => {
		if(isFtDef(val.pid)){
			treeMap.get(val.pid).sonList.push(val);
		}
	})
	
	//取pid为空的一级节点
	treeMap.forEach((val, key) =>{
		if(isFtUndef(val.pid)){
			completeTreeObj.sonList.push(val)
		}
	})
	
	return completeTreeObj
}

//funtree数据预处理
function Pretreatment(treeArray){
	//参数应该传入一个数组类型
	if(Array.isArray(treeArray)){
		treeArray.forEach(val => {
			//如果有sonList，则不用再添加sonList属性.没有sonList属性再添加
			if(isFtUndef(val.sonList)){
				val.sonList = []
			}
		})
	}
}


//定义组件
Vue.component('funtree',{
	template:'#node',
	data(){
		Pretreatment(treedata)
		return {
			node : complete(treedata)
		}
	},
	methods:{
		hasSonList(node){
			if(isFtDef(node.sonList)){
				return true
			}else{
				return false
			}
		}
	}
})

